package com.imti.xmlparserdemo;

import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonUtil
{

    private static Gson mGson = new Gson();

    public static List<Person> parsePersonList(String jsonString)
    {
        List<Person> personList = new ArrayList<>();

        try
        {
            JSONObject jsonObj = new JSONObject(jsonString);

            String states = jsonObj.getString("states");
            if ("200".equals(states))
            {
                JSONObject data = jsonObj.getJSONObject("data");

                if (data.has("persons"))
                {
                    JSONArray persons = data.getJSONArray("persons");

                    for (int i = 0; i < persons.length(); i++)
                    {
                        Person person = new Person();

                        person.setId(persons.getJSONObject(i).getInt("id"));
                        person.setName(persons.getJSONObject(i).getString("name"));
                        person.setAge(persons.getJSONObject(i).getInt("age"));

                        personList.add(person);
                    }
                }
            }

        } catch (JSONException e)
        {
            e.printStackTrace();
        }

        return personList;
    }

    public static HttpCommon parseCommon(String jsonString)
    {
        return mGson.fromJson(jsonString, HttpCommon.class);
    }
}
